package de.rj.urwalking.ui.activities;

import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.PreferenceManager;

import com.actionbarsherlock.app.SherlockPreferenceActivity;
import com.actionbarsherlock.view.MenuItem;

import de.rj.urwalking.R;
import de.rj.urwalking.config.Constants;
import de.rj.urwalking.util.PrefUtil;

@SuppressWarnings("deprecation")
// using the deprecated PreferenceActivity without Fragments since we just need a few simple settings (for now)
public class OutdoorPreferenceActivity extends SherlockPreferenceActivity implements OnSharedPreferenceChangeListener {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		addPreferencesFromResource(R.xml.outdoor_preferences);

		initSummaries();

	}

	private void initSummaries() {

		String radius = PrefUtil.readString(R.string.key_pref_radius, this, getString(R.string.pref_radius_default));
		findPreference(getString(R.string.key_pref_radius)).setSummary(radius + "m");

		String maxRadius = PrefUtil.readString(R.string.key_pref_max_radius, this,
				getString(R.string.pref_max_radius_default));
		findPreference(getString(R.string.key_pref_max_radius)).setSummary(maxRadius + "m");

		ListPreference poisPref = (ListPreference) findPreference(getString(R.string.key_pref_show_pois));
		poisPref.setSummary(poisPref.getEntries()[poisPref.findIndexOfValue(poisPref.getValue())]);

	}

	@Override
	protected void onResume() {
		super.onResume();
		getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// app icon in action bar clicked; go back
			finish();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

		if (key.equals(getString(R.string.key_pref_radius))) {
			findPreference(key).setSummary(
					sharedPreferences.getString(key, getString(R.string.pref_radius_default)) + "m");
		} else if (key.equals(getString(R.string.key_pref_max_radius))) {
			findPreference(key).setSummary(
					sharedPreferences.getString(key, getString(R.string.pref_max_radius_default)) + "m");
		} else if (key.equals(getString(R.string.key_pref_show_pois))) {
			ListPreference poisPref = (ListPreference) findPreference(key);
			poisPref.setSummary(poisPref.getEntries()[poisPref.findIndexOfValue(poisPref.getValue())]);
		}

	}
}
